package com.ruibang.glass.produce.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.produce.constant.Constants;
import com.ruibang.glass.produce.domain.req.MaterialPremixRecordReq;
import com.ruibang.glass.produce.entity.MaterialPremixRecord;
import com.ruibang.glass.produce.mapper.MaterialPremixRecordMapper;
import com.ruibang.glass.produce.service.MaterialPremixRecordService;
import com.ruibang.glass.produce.util.ExcelStyleUtils;
import com.teaming.cloud.framework2.autoconfigure.dynamic.datasource.annotation.DS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

/**
 * @Author: songJinKang
 * @CreateTime: 2024-03-11  15:38
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
@DS("emc")
public class MaterialPremixRecordServiceImpl extends ServiceImpl<MaterialPremixRecordMapper, MaterialPremixRecord> implements MaterialPremixRecordService {
    @Override
    public void deleteById(String id) {
        lambdaUpdate().eq(MaterialPremixRecord::getId, id).set(MaterialPremixRecord::getDelFlag, Constants.ONE_STR).update();
    }

    @Override
    public IPage<MaterialPremixRecord> pageQuery(MaterialPremixRecordReq materialPremixRecordReq) {
        return baseMapper.pageQuery(new Page<>(materialPremixRecordReq.getPageNo(), materialPremixRecordReq.getPageSize()),materialPremixRecordReq);
    }

    @Override
    public void export(MaterialPremixRecordReq materialPremixRecordReq, HttpServletResponse response) {
        materialPremixRecordReq.setPageNo(-1);
        materialPremixRecordReq.setPageSize(-1);
        IPage<MaterialPremixRecord> page = this.pageQuery(materialPremixRecordReq);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<MaterialPremixRecord> defectDirectlyList = page.getRecords();
            try {
                EasyExcel.write(response.getOutputStream(), MaterialPremixRecord.class)
                        .registerWriteHandler(ExcelStyleUtils.createTableStyle())
                        .sheet("history_data").doWrite(defectDirectlyList);
            } catch (IOException e) {
                log.error("数据导出失败：{}", e.getMessage());
            }
        }
    }

    @Override
    public List<MaterialPremixRecord> getByDate(LocalDate date) {
        return lambdaQuery().eq(MaterialPremixRecord::getDate, date).list();
    }

}
